/**
 * tabBar页面路径列表 (用于链接跳转时判断)
 * tabBarLinks为常量, 无需修改
 */
const tabBarLinks = [
  '/pages/index/index',
  '/pages/goods/list',
  '/pages/order/index',
  '/pages/user/user'
];

// 工具类
// const util = require('./utils/util.js');

App({
  /**
   * 全局变量
   */
  globalData: {
    user_id: null,
    navHeight:0,
    distribution_status:20,
    isFullSucreen: false,
    key: '27MBZ-XJ66U-4HZVK-BCA4T-Y2GKT-V7BXU',
    baseInfo:'',
    latitude: '',
    longitude: '',
    course_id:'',
    invite_code:''
  },
  // api地址
  api_root: '',
  siteInfo: require('siteinfo.js'),

  /**
   * 生命周期函数--监听小程序初始化
   */
  onLaunch: function(e) {
    let that = this
    wx.getSystemInfo({
      success: res => {
        //导航高度
        that.globalData.navHeight = res.statusBarHeight + 46;
        let modelmes = res.model;
        let iphoneArr = ['iPhone X', 'iPhone 11','iPhone 11 Pro Max','iPhone XS','iPhone XS Max','iPhone XR','iPhone 11 Pro','iPhone 12 mini','iPhone 12','iPhone 12 Pro','iPhone 12 Pro Max','iPhone13 mini','iPhone 13','iPhone13 Pro','iPhone13 Pro Max']
        iphoneArr.forEach(function (item) {
          if (modelmes.search(item) != -1) {
            that.globalData.isFullSucreen = true
          }
        }) 
      }, fail(err) {
        console.log(err);
      }
    })
    wx.setInnerAudioOption({
      obeyMuteSwitch: false,

      success: function (res) {
          console.log("开启静音模式下播放音乐的功能");
      },

      fail: function (err) {
          console.log("静音设置失败");
      },
  });
    // 设置api地址
    this.setApiRoot();
    // 小程序主动更新
    this.updateManager();
    // 小程序启动场景
    this.onStartupScene(e.query);
  },

  /**
   * 小程序启动场景
   */
  onStartupScene: function(query) {

    // 获取场景值
    let scene = this.getSceneData(query);
    // 记录推荐人id
    let refereeId = query.referee_id ? query.referee_id : scene.uid;
    refereeId > 0 && (this.saveRefereeId(refereeId));
  },

  /**
   * 记录推荐人id
   */
  saveRefereeId: function(refereeId) {
    if (!wx.getStorageSync('referee_id'))
      wx.setStorageSync('referee_id', refereeId);
  },

      /**
   * scene解码
   */
  scene_decode: function(e) {
    if (e === undefined)
      return {};
    let scene = decodeURIComponent(e),
      params = scene.split(','),
      data = {};
    for (let i in params) {
      var val = params[i].split(':');
      val.length > 0 && val[0] && (data[val[0]] = val[1] || null)
    }
    return data;
  },
    /**
   * 获取场景值(scene)
   */
  getSceneData: function(query) {
    return query.scene ? this.scene_decode(query.scene) : {};
  },

  /**
   * 当小程序启动，或从后台进入前台显示，会触发 onShow
   */
  onShow: function(options) {
    // 获取小程序基础信息
    this.getWxappBase();
  },

  /**
   * 设置api地址
   */
  setApiRoot: function() {
    this.api_root = this.siteInfo.siteroot;
  },
  // 获取配置信息
  getWxappBase(callback){
    let App = this;
    return new Promise((resolve, reject) => {
      App._post_form('index/config', {}, function(result) {
        console.log(result)
        // 记录小程序基础信息
        // wx.setStorageSync('wxapp', result.data.wxapp);
        App.globalData.baseInfo = result.data.config
        resolve(result.data.config); 
        callback && callback(result.data);
      });
    })
  },
  /**
   * 执行用户登录
   */
  doLogin: function() {
    // 保存当前页面
    let pages = getCurrentPages();
    if (pages.length) {
      let currentPage = pages[pages.length - 1];
      "pages/login/login" != currentPage.route &&
        wx.setStorageSync("currentPage", currentPage);
    }
    // 跳转授权页面
    wx.navigateTo({
      url: "/pages/login/login"
    });
  },

  /**
   * 当前用户id
   */
  getUserId: function() {
    return wx.getStorageSync('user_id');
  },

  /**
   * 显示成功提示框
   */
  showSuccess: function(msg, callback) {
    wx.showToast({
      title: msg,
      icon: 'success',
      mask: true,
      duration: 1500,
      success: function() {
        callback && (setTimeout(function() {
          callback();
        }, 1500));
      }
    });
  },

  /**
   * 显示失败提示框
   */
  showError: function(msg, callback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success: function(res) {
        // callback && (setTimeout(function() {
        //   callback();
        // }, 1500));
        callback && callback();
      }
    });
  },

  /**
   * get请求
   */
  _get: function(url, data, success, fail, complete, check_login) {
    let App = this;
    // 构造请求参数
    data = data || {};
    // data.wxapp_id = App.siteInfo.uniacid;

    // if (typeof check_login === 'undefined')
    //   check_login = true;

    // 构造get请求
    let request = function() {
      // data.token = wx.getStorageSync('token');
      wx.request({
        url: App.api_root + url,
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        data: data,
        success: function(res) {
          console.log(res)
          if (res.statusCode !== 200 || typeof res.data !== 'object') {
            console.log(res);
            App.showMsg(res.data.msg);
            return false;
          }
          if (res.data.status === 0) {
            // 登录态失效, 重新登录
            wx.hideLoading()
            // App.doLogin();
          } else if (res.data.status === -1) {
            App.showMsg(res.data.msg);
            return false;
          } else {
            success && success(res.data);
          }
        },
        fail: function(res) {
          console.log(res)
          App.showMsg(res.data.msg);
        },
        complete: function(res) {
          wx.hideLoading()
          complete && complete(res);
        },
      });
    };
    // 判断是否需要验证登录
    check_login ? App.doLogin(request) : request();
  },

  /**
   * post提交
   */
  _post_form: function(url, data, success, fail, complete) {
    let App = this;
    // data.wxapp_id = App.siteInfo.uniacid;
    // data.token = wx.getStorageSync('token');
    wx.request({
      url: App.api_root + url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token': wx.getStorageSync('token'),
        'dev': 'mini'
      },
      method: 'POST',
      data: data,
      success: function(res) {
        if (res.statusCode !== 200 || typeof res.data !== 'object') {
          App.showMsg(res.data.msg);
          return false;
        }
        if (res.data.status === 0) {
          // 登录态失效, 重新登录
          wx.hideNavigationBarLoading();
          // App.doLogin();
          return false;
        } else if (res.data.status === -1) {
          setTimeout(function(){
            App.showMsg(res.data.msg);
          },100)
          return false;
        }
        success && success(res.data);
      },
      fail: function(res) {
        // console.log(res);
        App.showMsg(res.data.msg);
      },
      complete: function(res) {
        setTimeout( () =>{
          wx.hideLoading();
        },1000)
        complete && complete(res);
      }
    });
  },
  /**
   * post提交(防止重复提交)
   */
  _post_form1: function(url, data, success, fail, complete) {
    let App = this;
    // data.wxapp_id = App.siteInfo.uniacid;
    wx.request({
      url: App.api_root + url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token': wx.getStorageSync('token')
      },
      method: 'POST',
      data: data,
      success: function(res) {
        if (res.statusCode !== 200 || typeof res.data !== 'object') {
          App.showMsg(res.data.msg);
        }
        if (res.data.status === 0) {
          // 登录态失效, 重新登录
          wx.hideNavigationBarLoading();
          // App.doLogin();
          return false;
        } else if (res.data.status === -1) {
          App.showMsg(res.data.msg);
        }
        success && success(res.data);
      },
      fail: function(res) {
        // console.log(res);
        App.showMsg(res.data.msg);
      },
      complete: function(res) {
        // wx.hideNavigationBarLoading();
        wx.hideLoading();
        complete && complete(res);
      }
    });
  },
  /**
   * 验证是否存在user_info
   */
  validateUserInfo: function() {
    let user_info = wx.getStorageSync('user_info');
    return !!wx.getStorageSync('user_info');
  },
  // 获取个人信息
  getuserInfo(){
    var that = this
    let App = this;
    return new Promise((resolve, reject) => {
      // 获取用户信息
      wx.request({
        url: App.api_root + 'member/member_info', //仅为示例，并非真实的接口地址
        data: {},
        header:{
          token:wx.getStorageSync('token')
        },
        method:'POST',
        success (va) {
          if(va.data.status == 1){
            console.log('已登录')
            resolve(va.data.data); 
          }else if(va.data.status == 0){
            wx.clearStorageSync('token')
            resolve(va.data.data);
          }else if(va.data.status == -1){
            App.showMsg(va.data.msg)
          }
        },
        fail(va){
          App.showMsg(va.data.msg)
        }
      })
    })
  },
  /**
   * 对象转URL
   */
  urlEncode: function(data) {
    var _result = [];
    for (var key in data) {
      var value = data[key];
      if (value.constructor == Array) {
        value.forEach(function(_value) {
          _result.push(key + "=" + _value);
        });
      } else {
        _result.push(key + '=' + value);
      }
    }
    return _result.join('&');
  },

  /**
   * 小程序主动更新
   */
  updateManager: function() {
    if (!wx.canIUse('getUpdateManager')) {
      return false;
    }
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    });
    updateManager.onUpdateReady(function() {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，即将重启应用',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      });
    });
    updateManager.onUpdateFailed(function() {
      // 新的版本下载失败
      wx.showModal({
        title: '更新提示',
        content: '新版本下载失败',
        showCancel: false
      })
    });
  },

  /**
   * 获取tabBar页面路径列表
   */
  getTabBarLinks: function() {
    return tabBarLinks;
  },

  /**
   * 跳转到指定页面
   * 支持tabBar页面
   */
  navigationTo: function(url) {
    if (!url || url.length == 0) {
      return false;
    }
    let tabBarLinks = this.getTabBarLinks();
    // tabBar页面
    if (tabBarLinks.indexOf(url) > -1) {
      wx.switchTab({
        url: url
      });
    } else {
      // 普通页面
      wx.navigateTo({
        url: url
      });
    }
  },

  /**
   * 记录formId
   */
  saveFormId: function(formId) {
    let App = this;
    console.log('saveFormId');
    if (formId === 'the formId is a mock one') {
      return false;
    }
    App._post_form('wxapp.formId/save', {
      formId: formId
    });
  },
  // 提示语
  showMsg: function (msg) {
    wx.showToast({
      icon: 'none',
      title: msg,
    })
  },
});